<template>
  <div class="edit-page">
    <BaseButton @click="goBack">
        <ChevronsLeft class="icon-base" />
      </BaseButton>
    <h2 class="page-title">修改密码</h2>
    <div class="form-group">
      <input type="password" placeholder="请输入原密码" v-model="oldPassword" />
      <input type="password" placeholder="请输入新密码" v-model="newPassword" />
      <input type="password" placeholder="确认新密码" v-model="confirmPassword" />
    </div>
    <button class="save-button" @click="updatePassword">保存修改</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import BaseButton from '@/components/BaseButton.vue'
import { useRouter } from 'vue-router';
import basicDetailIcon from '@/assets/icons/basic-detail.svg';
import { ChevronsLeft } from 'lucide-vue-next'
import axios from 'axios'  // 新增 axios 导入

const router = useRouter();
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const icons = { basicDetail: basicDetailIcon };

// 返回上一级页面
const goBack = () => router.go(-1);

// 更新密码的逻辑
const updatePassword = async () => {
  if (!oldPassword.value || !newPassword.value || !confirmPassword.value) {
    alert('所有字段均为必填项');
    return;
  }

  if (newPassword.value !== confirmPassword.value) {
    alert('两次输入的新密码不一致');
    return;
  }

  const currentUser = JSON.parse(localStorage.getItem('user'));
  const userId = currentUser ? currentUser.uid : null;

  if (!userId) {
    alert('未找到当前用户，请重新登录');
    return;
  }

  try {
    const response = await axios.put('/api/auth/information/password',
      {
        uid: userId,
        oldPassword: oldPassword.value,
        newPassword: newPassword.value
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': localStorage.getItem('token')
        }
      }
    );

    if (response.data.code === 0) {
      alert('密码修改成功');
      router.push('/edit'); // 密码修改成功后跳转到登录页
    } else {
      throw new Error(response.data.message || '修改失败');
    }
  } catch (error) {
    console.error('修改密码错误:', error);
    alert(error.response?.data?.message || error.message || '修改失败');
  }
};
</script>

<style scoped>
.edit-page {
  padding: var(--spacing-large);
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.icon-base {
  width: 24px;
  height: 24px;
  color: #1a1a1a;
}

.page-title {
  text-align: center;
  margin-top: 90px;
  font-size: var(--font-size-xlarge);
  color: #333;
}

.save-button {
  width: 100%;
  padding: 15px;
  background-color: var(--primary-color);
  color: var(--text-light);
  border: none;
  border-radius: var(--border-radius-small);
  margin-top: 20px;
  cursor: pointer;
}

input {
  margin-top: 20px;
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  background-color: #fff;
  color: #333;
}
</style>
